package com.shopping.action;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.shopping.base.BaseAction;
import com.shopping.config.Config;
import com.shopping.model.User;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {

	private static final long serialVersionUID = -3751062228769136274L;

	private Map<String, Object> result = null;
	private String newPwd = "";

	public UserAction() {
		result = new HashMap<String, Object>();
	}

	/**
	 * 
	 * @return 用户登录是否成功
	 * @throws Exception
	 */
	public String login() throws Exception {

		String ret = ERROR;
		boolean res = false;

		if (userService.login(model)) {
			User user = userService.getById(model.getId());
			ActionContext.getContext().getSession().put(Config.KEY_USER_SESSION, user);

			ret = SUCCESS;
			res = true;
		}

		result.put("res", res);
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("username", "heshun");
		userMap.put("id", "7410");
		userMap.put("grade", "20");
		result.put("user", userMap);
		
		return ret;
	}

	/**
	 * 用户注销
	 * 
	 * @return
	 * @throws Exception
	 */
	public String logout() throws Exception {
		ActionContext.getContext().getSession().remove(Config.KEY_USER_SESSION);
		return "toLogin";
	}

	/**
	 * 用户注册
	 * 
	 * @return
	 * @throws Exception
	 */
	public String register() throws Exception {

		if (userService.register(model)) {
			return "register";
		}
		return ERROR;
	}

	/**
	 * 修改用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String update() throws Exception {
		if (userService.update(model)) {
			return "update";
		}
		return ERROR;
	}

	/**
	 * 用户修改密码
	 * 
	 * @return
	 * @throws Exception
	 */
	public String changePwd() throws Exception {
		User user = getCurrentUser();
		if (user != null) {
			userService.changerPwd(user, newPwd);
			return SUCCESS;
		}
		return ERROR;
	}

	public Map<String, Object> getResult() {
		return result;
	}

	public void setResult(Map<String, Object> result) {
		this.result = result;
	}

	public String getNewPwd() {
		return newPwd;
	}

	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}

}
